package com.ryskoo.config.shiro;

import com.ryskoo.framework.core.utils.RedisUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

@Service
public class RedisSessionDAO extends AbstractSessionDAO {
	private static final long EXPIRE_TIMES = 1 * 24 * 60 * 60;

	@Autowired
	private RedisUtil redisClient;

	@Override
	public void update(Session session) throws UnknownSessionException {
		if (session != null) {
			redisClient.setExpireSession(session.getId().toString(), session,
					EXPIRE_TIMES);
		}
	}

	@Override
	public void delete(Session session) {
		redisClient.remove(session.getId().toString());
	}

	@Override
	public Collection<Session> getActiveSessions() {
		return new ArrayList<Session>();
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = generateSessionId(session);
		System.out.println("sessionId====" + sessionId);
		assignSessionId(session, sessionId);
		redisClient.setExpireSession(session.getId().toString(), session,
				EXPIRE_TIMES);
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		Session session = (Session) redisClient
				.getSession(sessionId.toString());
		if (null != session) {
			redisClient.setExpireTime(sessionId.toString(), EXPIRE_TIMES);
			return session;
		}
		return null;
	}
}
